const overtimeModel = require('../modules/overtimemodules')
const moment = require('moment');
const xlsx= require ('node-xlsx');
const urlencode = require('urlencode');
const dateConfig=require('../config/dateconfig')
const excelConfig=require('../config/excelconfig')
const fs=require('fs')
const path =require('path');
class overtimeController {
    
    /**上传打卡记录 */
    static async uploadex(ctx){
        let req = ctx.req.body;
        if(ctx.req.file&&ctx.req.file.path){
            var str=ctx.req.file.path;
            req.iconUrl=str.substring(str.indexOf("\\"));
            await initdata(str,ctx);
        }
    }
    /**导出报表 */
    static async exportex(ctx){
            let data= await overtimeModel.getUserByLoginName("郭祖容",'2018-12-29 00:00:00','2019-12-30 00:00:00');
            var arr=new Array();
            for(let i=0;i<data.length;i++){
                arr.push(data[i].dataValues)
            }
            exportExcel(ctx,excelConfig.checktime,arr,"dssd");
            ctx.response.status = 200;
    }
    
}
/**解析考勤Excel文件并且存到数据库 */
async function initdata(str,ctx) {
    var datajson = xlsx.parse(path.join(__dirname,'../')+`${str}`);
    var firstSheet = datajson[0].data;
    var insertval = new Array();
    if(firstSheet[0][0]=="加班单申请"&&firstSheet[2][0]=="主表ID_系统字段"&&firstSheet[2][1]=="姓名"
    &&firstSheet[2][2]=="部门"&&firstSheet[2][3]=="二级部门"&&firstSheet[2][4]=="工号"){
        //定义实体类数组
        var checktime = new Array('overtimeid', 'Name', 'DEFAULTDEPTID', 'secondDEFAULTDEPTID', 'SSN', 'startTIME', 'endTIME','category', 'total','suggestion','state');
        var res=new Array();
        for (var i = 3; i < firstSheet.length; i++) {
            let cdata = firstSheet[i];
            let odate = new Object();
            for (let j = 0; j < cdata.length; j++) {
                odate[checktime[j]] = cdata[j];
            }
            console.log(odate);
            insertval.push(odate)
            if (i % 1000 == 0) {
            let te= await overtimeModel.createOvertimes(insertval);
            res.push(te);
            insertval.splice(0, insertval.length)
            }
        }
        await overtimeModel.createOvertimes(insertval);
        ctx.response.status = 200;
            ctx.body = {
                code: 200,
                msg:'上传成功',
                data:''
            }
    }else{
        ctx.response.status = 200;
        ctx.body = {
            code: 500,
            msg:'上传失败，文件格式有误',
            data:''
        } 
    }
}
/**导出Excel表格 */
async function exportExcel(ctx,config,listData,exclename){
    let excelConfig = [];
    excelConfig.push(config.map(item => {
        return item.title
    }))
    listData.forEach(list => {
        excelConfig.push(config.map(item => {
            //const value = list[item.column];
            return item.column!='CHECKTIME'?list[item.column]:moment(list[item.column]).format('YYYY-MM-DD HH:mm:ss');
        }))
    })
    console.log(excelConfig);
    let buffer = xlsx.build([{
        name: exclename,
        data: excelConfig
    }]);
    
    let name = urlencode(exclename + '_' + (+new Date()) + '.xlsx', "utf-8");;
    console.log(name);
    ctx.set('Content-Type', 'application/vnd.ms-excel;charset=UTF-8'); 
    ctx.set("Content-Disposition", "attachment; filename=" + name);
    ctx.body = {
                code: 200,
                msg:'导出成功',
                data:buffer
                }

}

module.exports = overtimeController